import {
  getMemberOrderPreAPI,
  getMemberOrderPreNowAPI,
  getMemberOrderRepurchaseByIdAPI,
  postMemberOrderAPI,
} from '@/services/order'
import { useAddressStore } from '@/stores/modules/address'
import type { OrderPreResult } from '@/types/order'
import { onLoad } from '@dcloudio/uni-app'
import { computed, reactive, ref } from 'vue'

const useCreateHooks = () => {
  // 获取屏幕边界到安全区域距离
  const { safeAreaInsets } = uni.getSystemInfoSync()
  // 订单备注
  const buyerMessage = ref('')
  // 配送时间
  const deliveryList = ref([
    { type: 1, text: '时间不限 (周一至周日)' },
    { type: 2, text: '工作日送 (周一至周五)' },
    { type: 3, text: '周末配送 (周六至周日)' },
  ])
  // 当前配送时间下标
  const activeIndex = ref(0)
  // 当前配送时间
  const activeDelivery = computed(() => deliveryList.value[activeIndex.value])
  // 修改配送时间
  const onChangeDelivery: UniHelper.SelectorPickerOnChange = (ev) => {
    activeIndex.value = ev.detail.value
  }

  // 页面参数
  const query = reactive<{
    skuId?: string
    count?: string
    orderId?: string
  }>({})

  // 获取订单信息
  const orderPre = ref<OrderPreResult>()
  const getMemberOrderPreData = async () => {
    if (query.count && query.skuId) {
      const res = await getMemberOrderPreNowAPI({
        count: query.count,
        skuId: query.skuId,
      })
      orderPre.value = res.result
    } else if (query.orderId) {
      // 再次购买
      const res = await getMemberOrderRepurchaseByIdAPI(query.orderId)
      orderPre.value = res.result
    } else {
      const res = await getMemberOrderPreAPI()
      orderPre.value = res.result
    }
  }

  const addressStore = useAddressStore()
  // 收货地址
  const selecteAddress = computed(() => {
    return addressStore.selectedAddress || orderPre.value?.userAddresses.find((v) => v.isDefault)
  })

  // 提交订单
  const onOrderSubmit = async () => {
    // 没有收货地址提醒
    if (!selecteAddress.value?.id) {
      return uni.showToast({ icon: 'none', title: '请选择收货地址' })
    }
    // 发送请求
    const res = await postMemberOrderAPI({
      addressId: selecteAddress.value?.id,
      buyerMessage: buyerMessage.value,
      deliveryTimeType: activeDelivery.value.type,
      goods: orderPre.value!.goods.map((v) => ({ count: v.count, skuId: v.skuId })),
      payChannel: 2,
      payType: 1,
    })
    // 关闭当前页面，跳转到订单详情，传递订单id
    uni.redirectTo({ url: `/pagesOrder/detail/detail?id=${res.result.id}` })
  }

  onLoad((options) => {
    query.count = options!.count
    query.orderId = options!.orderId
    query.skuId = options!.skuId
    getMemberOrderPreData()
  })

  return {
    selecteAddress,
    orderPre,
    deliveryList,
    onChangeDelivery,
    activeDelivery,
    buyerMessage,
    safeAreaInsets,
    onOrderSubmit,
  }
}

export default useCreateHooks
